import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/fwebView_scaffold.dart';
import 'package:gzmall_app/common/launch_util.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/setting_util.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/goods/goods_details_page.dart';
import 'package:gzmall_app/mine/logistics.dart';
import 'package:gzmall_app/mine/order_product_comment_page.dart';
import 'package:gzmall_app/model/order.dart';
import 'package:gzmall_app/model/order_item.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:gzmall_app/model/user.dart';
import 'package:gzmall_app/shoppping_cart/buy_success.dart';
import 'package:tobias/tobias.dart' as tobias;
import 'package:gzmall_app/model/wechat_pay_info.dart';
import 'package:gzmall_app/mine/order_after_sale_page.dart';

class OrderDetailsPage extends StatefulWidget {
  int id;
  String title;
  String params;
  String type;

  OrderDetailsPage({this.id, this.title, this.params, this.type = ''});

  @override
  State<StatefulWidget> createState() => OrderDetailsPageState(
      id: this.id, title: this.title, params: this.params, type: this.type);
}

class OrderDetailsPageState extends State<OrderDetailsPage> {
  int id;
  String title;
  String params;
  String type;

  Order _order;

  OrderDetailsPageState({this.id, this.title, this.params, this.type = ''});

  @override
  void initState() {
    super.initState();
    fluwx.registerWxApi(appId: Api.wxAppId);
    fluwx.weChatResponseEventHandler.listen((data) {
      if (data is fluwx.WeChatPaymentResponse) {
        print("<fluwx> fluwx.weChatResponseEventHandler.listen");
        print("<fluwx> data.type " + data.type.toString());
        print("<fluwx> data.errCode " + data.errCode.toString());
        print("<fluwx> data.extData " + data.extData.toString());

        if (data != null && data.errCode != null) {
          switch (data.errCode) {
            case 0:
              // 成功 展示成功页面
              Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                return new BuySuccessPage(
                    _order.totalFee.toString(), id.toString());
              })).then((value) {
                Navigator.of(context).pop();
                _getOrdersDetail(id);
              });
              break;
            case -1:
              // 错误 可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。
              ToastUtil.showMessageToast(data.errStr ?? "微信支付错误");
              Navigator.of(context).pop();
              _getOrdersDetail(id);
              break;
            case -2:
              // 用户取消 无需处理。发生场景：用户不支付了，点击取消，返回APP。
              break;
          }
        }
      }
    });
    if (this.type == "after_sale") {
      _getOrderItem(id);
      return;
    }
    _getOrdersDetail(id);
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> orderItemWidget = [];
    if (_order != null && _order.items != null && _order.items.length > 0) {
      orderItemWidget =
          _order.items.map((item) => _createOrderItemWidget(item)).toList();
    }
    List<Widget> _ctlBtns = [];
    List<Widget> _ctl2Btns = [];
    if (_order != null) {
      switch (_order.state) {
        case "pending":
          _ctlBtns.add(Padding(
            padding: const EdgeInsets.only(right: 15.0),
            child: _getCtlBtnWidget(
                "取消订单", Colors.white, ColorCommon.black1, ColorCommon.black1,
                () {
              // _updateOrder(_order.id, "cancel");
              _cancelOrder(_order.id);
            }),
          ));
          _ctlBtns.add(_getCtlBtnWidget("立即付款", ColorCommon.primaryColor,
              Colors.white, ColorCommon.primaryColor, () {
            // _updateOrder(_order.id, "checkouted");
            _showPayWay(context);
          }));
          break;
        case "checkouted":
          // _ctlBtns.add(Padding(
          //   padding: const EdgeInsets.only(right: 10.0),
          //   child: _getCtlBtnWidget(
          //       "退款", Colors.white, ColorCommon.black1, ColorCommon.black1, () {
          //     _refundOrder(_order.id);
          //   }),
          // ));
          // _ctlBtns.add(_getCtlBtnWidget(
          //     "提醒物流", Colors.white, ColorCommon.black1, ColorCommon.black1, () {
          //   ToastUtil.showMessageToast("已帮您提醒物流, 请耐心等待");
          // }));
          _ctlBtns.add(_getCtlBtnWidget(
              "退款", Colors.white, ColorCommon.black1, ColorCommon.black1, () {
            _refundOrder(_order.id);
          }));
          break;
        case "sent":
          // _ctlBtns.add(_getCtlBtnWidget(
          //     "催物流", Colors.white, ColorCommon.black1, ColorCommon.black1, () {
          //   ToastUtil.showMessageToast("已帮您催促物流, 请耐心等待");
          // }));
          // _ctlBtns.add(Padding(
          //     padding: const EdgeInsets.only(left: 10.0),
          //     child: _getCtlBtnWidget(
          //         "查看物流", Colors.white, ColorCommon.black1, ColorCommon.black1,
          //         () {
          //       Navigator.of(context).push(MaterialPageRoute(builder: (_) {
          //         return LogisticsPage(_order.id);
          //       }));
          //     })));
          _ctlBtns.add(_getCtlBtnWidget(
              "查看物流", Colors.white, ColorCommon.black1, ColorCommon.black1, () {
            Navigator.of(context).push(MaterialPageRoute(builder: (_) {
              return LogisticsPage(_order.id);
            }));
          }));
          _ctlBtns.add(Padding(
              padding: const EdgeInsets.only(left: 10.0),
              child: _getCtlBtnWidget("确认收货", ColorCommon.primaryColor,
                  Colors.white, ColorCommon.primaryColor, () {
                // _updateOrder(_order.id, "completed");
                _completeOrder(_order.id);
              })));
          break;
        case "completed":
          _ctlBtns.add(Padding(
            padding: const EdgeInsets.only(right: 10.0),
            child: _getCtlBtnWidget(
                "删除订单", Colors.white, ColorCommon.black1, ColorCommon.black1,
                () {
              _deleteOrder(_order.id);
            }),
          ));
          _ctlBtns.add(
            _getCtlBtnWidget(
                "查看物流", Colors.white, ColorCommon.black1, ColorCommon.black1,
                () {
              Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                return LogisticsPage(_order.id);
              }));
            }),
          );
          if (_order != null && !_order.isEvaluated) {
            _ctlBtns.add(Padding(
                padding: const EdgeInsets.only(left: 10.0),
                child: _getCtlBtnWidget("评价", ColorCommon.primaryColor,
                    Colors.white, ColorCommon.primaryColor, () {
                  Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                    return OrderProductCommentPage(_order.id);
                  })).then((v) {
                    _getOrdersDetail(id);
                  });
                })));
          }
          break;
        case "cancel":
          _ctlBtns.add(_getCtlBtnWidget(
              "删除订单", Colors.white, ColorCommon.black1, ColorCommon.black1, () {
            _deleteOrder(_order.id);
          }));
          break;
        default:
          break;
      }
    }

    return Scaffold(
      appBar: _createAppBar(),
      body: Container(
        color: ColorCommon.grey5,
        child: ListView(children: <Widget>[
          // GestureDetector(
          //   onTap: () {
          //     Navigator.of(context).pushNamed("/logistics");
          //   },
          //   child: Container(
          //     color: Colors.red,
          //     margin: const EdgeInsets.only(top: 20.0),
          //     padding: const EdgeInsets.only(
          //         left: 10.0, right: 10.0, top: 15.0, bottom: 15.0),
          //     child: Row(
          //         mainAxisAlignment: MainAxisAlignment.start,
          //         crossAxisAlignment: CrossAxisAlignment.start,
          //         children: <Widget>[
          //           Row(
          //             children: <Widget>[
          //               Icon(
          //                 Icons.timer,
          //                 color: Colors.white,
          //               ),
          //               Padding(
          //                 padding: const EdgeInsets.only(left: 10.0),
          //                 child: Text(
          //                   "正在出库",
          //                   style:
          //                       TextStyle(fontSize: 20.0, color: Colors.white),
          //                 ),
          //               ),
          //             ],
          //           ),
          //           Expanded(
          //             child: Column(
          //               mainAxisAlignment: MainAxisAlignment.end,
          //               crossAxisAlignment: CrossAxisAlignment.end,
          //               children: <Widget>[
          //                 Text(
          //                   "布吉岛",
          //                   style:
          //                       TextStyle(fontSize: 14.0, color: Colors.white),
          //                 ),
          //                 Text(
          //                   "预计2017/05/20,9:00-15:00送达",
          //                   style:
          //                       TextStyle(fontSize: 14.0, color: Colors.white),
          //                 ),
          //               ],
          //             ),
          //           ),
          //         ]),
          //   ),
          // ),
          // Container(
          //   height: 75.0,
          //   color: Colors.white,
          //   padding: const EdgeInsets.only(
          //       left: 10.0, right: 10.0, top: 15.0, bottom: 15.0),
          //   margin: const EdgeInsets.only(top: 10.0),
          //   child: Row(
          //     mainAxisAlignment: MainAxisAlignment.start,
          //     crossAxisAlignment: CrossAxisAlignment.start,
          //     children: <Widget>[
          //       Icon(Icons.time_to_leave),
          //       Expanded(
          //         child: Container(
          //           margin: const EdgeInsets.only(left: 10.0),
          //           child: Column(
          //               mainAxisAlignment: MainAxisAlignment.spaceBetween,
          //               crossAxisAlignment: CrossAxisAlignment.start,
          //               children: <Widget>[
          //                 Text(
          //                   "您的订单预计5月20日送达您手中",
          //                   style: TextStyle(
          //                       fontSize: 16.0, color: ColorCommon.black1),
          //                 ),
          //                 Text(
          //                   "2017-05-19 17:02:43",
          //                   style: TextStyle(
          //                       fontSize: 16.0, color: ColorCommon.grey3),
          //                 ),
          //               ]),
          //         ),
          //       ),
          //       Container(
          //         height: 45.0,
          //         child: Icon(Icons.arrow_right),
          //       ),
          //     ],
          //   ),
          // ),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.only(
                left: 10.0, right: 10.0, top: 15.0, bottom: 15.0),
            margin: const EdgeInsets.only(top: 10.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Image.asset(
                  "images/address.png",
                  width: 25.0,
                  height: 25.0,
                ),
                Expanded(
                  child: Container(
                      margin: const EdgeInsets.only(left: 10.0),
                      child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              _order != null &&
                                      _order.buyerName != null &&
                                      _order.buyerPhone != null
                                  ? "" +
                                      _order.buyerName +
                                      " " +
                                      _order.buyerPhone
                                  : "",
                              style: TextStyle(
                                  fontSize: 16.0, color: ColorCommon.black1),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 8.0),
                              child: Text(
                                _order != null && _order.address != null
                                    ? "地址: " + _order.address
                                    : "地址: ",
                                style: TextStyle(
                                    fontSize: 16.0, color: ColorCommon.grey3),
                              ),
                            ),
                          ])),
                ),
              ],
            ),
          ),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.only(
                top: 10.0, bottom: 10.0, left: 15.0, right: 15.0),
            margin: const EdgeInsets.only(top: 10.0),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Text(
                    _order?.shopName ?? SettingUtil.appName,
                    style: TextStyle(fontSize: 22.0, color: ColorCommon.black1),
                  ),
                ),
                // InkWell(
                //   onTap: () {
                //     User.isLogin().then((v) {
                //       if (v) {
                //         if (_order != null &&
                //             _order.serviceUrl != null &&
                //             _order.serviceUrl.isNotEmpty) {
                //           Navigator.of(context)
                //               .push(new MaterialPageRoute(builder: (_) {
                //             return FWebviewScaffold(
                //               url: _order.serviceUrl,
                //               userAgent: Api.kWebViewUserAgent,
                //               enableMessaging: true,
                //               withJavascript: true,
                //               clearCache: true,
                //               appBar: AppBar(
                //                 title: Text((_order?.shopName ?? "") + "客服"),
                //               ),
                //             );
                //           }));
                //           return;
                //         }
                //       } else {
                //         Navigator.of(context)
                //             .pushNamed('/login_page')
                //             .then((v) {});
                //       }
                //     });
                //   },
                //   child: Padding(
                //     padding: const EdgeInsets.only(right: 8.0),
                //     child: Text(
                //       "联系客服",
                //       style:
                //           TextStyle(fontSize: 16.0, color: ColorCommon.black1),
                //     ),
                //   ),
                // ),
                // Image.asset(
                //   "images/service.png",
                //   width: 20.0,
                //   height: 20.0,
                // ),
              ],
            ),
          ),
          Column(
            children: orderItemWidget,
          ),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.only(
                left: 15.0, right: 15.0, top: 5.0, bottom: 10.0),
            margin: const EdgeInsets.only(top: 10.0),
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.only(right: 15.0),
                        child: Text(
                          _order != null && _order.tradeNo != null
                              ? "订单编号: " + _order.tradeNo
                              : "订单编号: ",
                          style: TextStyle(
                              fontSize: 16.0, color: ColorCommon.black1),
                        ),
                      ),
                      // Chip(
                      //   backgroundColor: Colors.white,
                      //   label: Text("复制"),
                      //   labelPadding:
                      //       const EdgeInsets.only(left: 15.0, right: 15.0),
                      //   padding: const EdgeInsets.only(top: 2.0, bottom: 2.0),
                      //   shape: RoundedRectangleBorder(
                      //       borderRadius: BorderRadius.circular(0.0),
                      //       side: BorderSide(
                      //           color: ColorCommon.grey5, width: 1.0)),
                      // ),
                    ],
                  ),
                  Text(
                    _order != null &&
                            _order.createdAt != null &&
                            _order.createdTimeAt != null
                        ? "下单时间: " + _order.createdAt + _order.createdTimeAt
                        : "下单时间: ",
                    style: TextStyle(fontSize: 16.0, color: ColorCommon.black1),
                  ),
                ]),
          ),
          this.type != 'after_sale'
              ? Container(
                  margin: const EdgeInsets.only(top: 15.0, bottom: 20.0),
                  padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                  child: Column(
                    children: <Widget>[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: _ctlBtns,
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 10.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: _ctl2Btns,
                        ),
                      ),
                    ],
                  ),
                )
              : Container(),
        ]),
      ),
    );
  }

  _createAppBar() {
    return AppBar(
      elevation: 0.0,
      title: Text("订单详情"),
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
    );
  }

  Widget _createOrderItemWidget(OrderItem item) {
    return InkWell(
        onTap: () {
          Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
            return new GoodsDetailsPage(productId: item.spuId);
          }));
        },
        child: Column(
          children: <Widget>[
            Container(
              color: Colors.white,
              margin: const EdgeInsets.only(top: 1.0),
              padding: const EdgeInsets.only(
                  left: 15.0, right: 15.0, top: 10.0, bottom: 10.0),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  item != null && item.avatar != null
                      ? CachedNetworkImage(
                          width: 100.0,
                          height: 100.0,
                          imageUrl: item.avatar,
                          fit: BoxFit.fill,
                        )
                      : Container(
                          color: ColorCommon.grey2,
                          width: 100.0,
                          height: 100.0,
                        ),
                  Expanded(
                    child: Container(
                      margin: const EdgeInsets.only(left: 10.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            item?.name,
                            style: TextStyle(
                                fontSize: 18.0, color: ColorCommon.black1),
                          ),
                          Text(
                            "数量: " +
                                item?.quantity.toString() +
                                " " +
                                item?.optionValuePresentation,
                            style: TextStyle(
                                fontSize: 14.0, color: ColorCommon.grey3),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(top: 10.0),
                            child: Text(
                              "¥" + item?.fee.toString(),
                              style: TextStyle(
                                  fontSize: 18.0, color: ColorCommon.black1),
                            ),
                          ),
                          item.state == "sent" || item.state == "completed"
                              ? Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: <Widget>[
                                    _getButtonView(
                                        "申请售后",
                                        Colors.white,
                                        ColorCommon.black1,
                                        ColorCommon.grey4, () {
                                      Navigator.of(context)
                                          .push(MaterialPageRoute(builder: (_) {
                                        return OrderAfterSalePage(
                                            _order.items[0]);
                                      })).then((v) {
                                        if (v) {
                                          _getOrdersDetail(id);
                                        }
                                      });
                                    }),
                                  ],
                                )
                              : Container(),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Container(
              color: ColorCommon.grey2,
              padding: const EdgeInsets.only(
                  left: 15.0, right: 15.0, bottom: 10.0, top: 10.0),
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: Text(
                      "服务: 商品全面无忧保障",
                      style:
                          TextStyle(fontSize: 14.0, color: ColorCommon.grey3),
                    ),
                  ),
                  Text(
                    "立即购买",
                    style: TextStyle(fontSize: 14.0, color: ColorCommon.grey3),
                  ),
                  Image.asset(
                    "images/right_arrow.png",
                    width: 10.0,
                    height: 10.0,
                  ),
                ],
              ),
            ),
          ],
        ));
  }

  Widget _getCtlBtnWidget(String text, Color bgColor, Color fontColor,
      Color borderColor, Function onTap) {
    return InkWell(
      onTap: onTap,
      child: Container(
        height: 32.0,
        alignment: Alignment.center,
        padding: const EdgeInsets.only(left: 10.0, right: 10.0),
        decoration: BoxDecoration(
            color: bgColor, border: Border.all(color: borderColor, width: 1.0)),
        child: Text(
          text,
          style: TextStyle(fontSize: 14.0, color: fontColor),
        ),
      ),
    );
  }

  _getButtonView(String text, Color bgColor, Color contentColor,
      Color borderColor, GestureTapCallback onTap) {
    return Container(
      height: 30.0,
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 8.0, right: 8.0),
      decoration: BoxDecoration(
          color: bgColor,
          borderRadius: BorderRadius.circular(100.0),
          border: Border.all(color: borderColor, width: 1.0)),
      child: GestureDetector(
        onTap: onTap,
        child: Text(
          text,
          style: TextStyle(fontSize: 12.0, color: contentColor),
        ),
      ),
    );
  }

  _showPayWay(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(15.0),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Align(
                child: Text(
                  "确认付款",
                  style: TextStyle(fontSize: 16.0, color: ColorCommon.black1),
                ),
              ),
              Align(
                alignment: Alignment.center,
                child: Padding(
                  padding: const EdgeInsets.only(top: 20.0, bottom: 20.0),
                  child: Text(
                    "¥ " + _order.totalFee.toString(),
                    style: TextStyle(
                      fontSize: 36.0,
                      color: ColorCommon.primaryColor,
                    ),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(bottom: 10.0),
                child: Text(
                  "付款方式",
                  style: TextStyle(fontSize: 15.0, color: ColorCommon.black1),
                ),
              ),
              Expanded(
                child: ListView(
                  padding: const EdgeInsets.only(top: 0.0),
                  children: <Widget>[
                    InkWell(
                      onTap: () {
                        List<String> _ids = [];
                        _ids.add(_order.id.toString());
                        if (_ids.length > 0) {
                          _getPayInfo(_ids, "moneybag");
                        } else {
                          ToastUtil.showMessageToast("下单错误, 请重试");
                        }
                      },
                      child: Container(
                        color: ColorCommon.grey5,
                        padding: const EdgeInsets.only(
                            left: 15.0, right: 15.0, bottom: 10.0, top: 10.0),
                        margin: const EdgeInsets.only(bottom: 10.0),
                        child: Row(children: <Widget>[
                          Image.asset(
                            "images/money_bag.png",
                            width: 30.0,
                            height: 30.0,
                          ),
                          Padding(
                            padding:
                                const EdgeInsets.only(left: 10.0, right: 10.0),
                            child: Text(
                              "钱包支付",
                              style: TextStyle(
                                  fontSize: 15.0, color: ColorCommon.black1),
                            ),
                          )
                        ]),
                      ),
                    ),
                    LaunchUtil.isInstallWeixin && !SettingUtil.isAppStoreAudit()
                        ? InkWell(
                            onTap: () {
                              List<String> _ids = [];
                              _ids.add(_order.id.toString());
                              if (_ids.length > 0) {
                                _getPayInfo(_ids, "wepay");
                              } else {
                                ToastUtil.showMessageToast("下单错误, 请重试");
                              }
                            },
                            child: Container(
                              color: ColorCommon.grey5,
                              padding: const EdgeInsets.only(
                                  left: 15.0,
                                  right: 15.0,
                                  bottom: 10.0,
                                  top: 10.0),
                              margin: const EdgeInsets.only(bottom: 10.0),
                              child: Row(children: <Widget>[
                                Image.asset(
                                  "images/wechat.png",
                                  width: 30.0,
                                  height: 30.0,
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(
                                      left: 10.0, right: 10.0),
                                  child: Text(
                                    "微信支付",
                                    style: TextStyle(
                                        fontSize: 15.0,
                                        color: ColorCommon.black1),
                                  ),
                                )
                              ]),
                            ),
                          )
                        : Container(),
                    LaunchUtil.isInstallAlipay && !SettingUtil.isAppStoreAudit()
                        ? InkWell(
                            onTap: () {
                              List<String> _ids = [];
                              _ids.add(_order.id.toString());
                              if (_ids.length > 0) {
                                _getPayInfo(_ids, "alipay");
                              } else {
                                ToastUtil.showMessageToast("下单错误, 请重试");
                              }
                            },
                            child: Container(
                              color: ColorCommon.grey5,
                              padding: const EdgeInsets.only(
                                  left: 15.0,
                                  right: 15.0,
                                  bottom: 10.0,
                                  top: 10.0),
                              margin: const EdgeInsets.only(bottom: 10.0),
                              child: Row(children: <Widget>[
                                Image.asset(
                                  "images/alipay.png",
                                  width: 30.0,
                                  height: 30.0,
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(
                                      left: 10.0, right: 10.0),
                                  child: Text(
                                    "支付宝",
                                    style: TextStyle(
                                        fontSize: 15.0,
                                        color: ColorCommon.black1),
                                  ),
                                ),
                              ]),
                            ),
                          )
                        : Container(),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  _getOrdersDetail(int id) {
    Map<String, Object> params = {};
    if (this.params != null && this.params.isNotEmpty) {
      Map<String, dynamic> otherParams = json.decode(this.params);
      params.addAll(otherParams);
    }
    String _idVal = id != null
        ? id.toString()
        : (params["id"] != null ? params["id"].toString() : "");
    NetUtil.get(context, Api.orders + "/" + _idVal, (data, message) {
      if (!mounted) return;
      setState(() {
        _order = Order.fromJson(data);
      });
    });
  }

  _updateOrder(int id, String state) {
    FormData formData = new FormData.fromMap({
      "state": state,
    });

    NetUtil.put(
      context,
      Api.orders + "/" + id.toString(),
      (data, message) {
        ToastUtil.showMessageToast(message);

        if (!mounted) return;
        setState(() {
          _order.state = state;
        });
      },
      params: formData,
    );
  }

  _getPayInfo(List<String> orderIds, String payMethod) async {
    Map<String, Object> params = {
      "orders": orderIds.join(","),
      "pay_method": payMethod,
    };

    NetUtil.post(context, Api.pay, (data, message) {
      ToastUtil.showMessageToast(message);

      if (payMethod == "wepay") {
        // 微信支付
        WechatPayInfo wechatPayInfo = WechatPayInfo.fromJson(data);
        fluwx
            .payWithWeChat(
                appId: wechatPayInfo.appid,
                partnerId: wechatPayInfo.partnerid,
                prepayId: wechatPayInfo.prepayid,
                packageValue: wechatPayInfo.package,
                nonceStr: wechatPayInfo.noncestr,
                timeStamp: int.parse(wechatPayInfo.timestamp),
                sign: wechatPayInfo.sign)
            .then((value) {
          print("<fluwx> then(value) ${value}");
        });
      } else if (payMethod == "alipay") {
        // 支付宝支付
        _callAlipay(data);
      } else if (payMethod == "moneybag") {
        Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
          return new BuySuccessPage(_order.totalFee.toString(), id.toString());
        })).then((value) {
          Navigator.of(context).pop();
          _getOrdersDetail(id);
        });
      }
    }, params: params, isShowLoading: true);
  }

  _callAlipay(String payInfo) async {
    Map payResult = {};
    try {
      payResult = await tobias.aliPay(payInfo);
      print("<tobias> $payResult");
      if (payResult != null && payResult["resultStatus"] != null) {
        switch (payResult["resultStatus"].toString()) {
          case "9000":
            // 订单支付成功
            Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
              return new BuySuccessPage(
                  _order.totalFee.toString(), id.toString());
            })).then((value) {
              Navigator.of(context).pop();
              _getOrdersDetail(id);
            });
            break;
          case "6001":
            // 用户中途取消
            break;
          default:
            // 支付失败
            ToastUtil.showMessageToast(payResult["memo"]);
            Navigator.of(context).pop();
            _getOrdersDetail(id);
            break;
        }
      }
    } on Exception catch (e) {
      print("<tobias> $e");
    }
  }

  _refundOrder(int id) {
    NetUtil.post(context, Api.orders + "/" + id.toString() + "/refund",
        (data, message) {
      ToastUtil.showMessageToast(message);
      // _getOrdersDetail(id);
      if (!mounted) return;
      setState(() {
        _order = Order.fromJson(data);
      });
    }, isShowLoading: true);
  }

  _cancelOrder(int id) {
    NetUtil.post(context, Api.orders + "/" + id.toString() + "/cancel",
        (data, message) {
      ToastUtil.showMessageToast(message);
      _getOrdersDetail(id);
    }, isShowLoading: true);
  }

  _deleteOrder(int id) {
    NetUtil.delete(
      context,
      Api.orders + "/" + id.toString(),
      (data, message) {
        ToastUtil.showMessageToast(message);
        Navigator.of(context).pop();
      },
    );
  }

  _completeOrder(int id) {
    NetUtil.post(context, Api.orders + "/" + id.toString() + "/complete",
        (data, message) {
      ToastUtil.showMessageToast(message);
      _getOrdersDetail(id);
    }, isShowLoading: true);
  }

  _getOrderItem(int id) {
    NetUtil.get(context, Api.orderItems + "/" + id.toString(), (data, message) {
      if (!mounted) return;
      setState(() {
        _order = Order.fromJson(data);
      });
    });
  }
}
